package team.pra.manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.pra.manager.common.PageHelper;
import team.pra.manager.service.AccountService;
import team.pra.manager.common.ManagerResult;
import team.pra.manager.common.PageBean;
import team.pra.manager.mapper.AccountMapper;
import team.pra.manager.pojo.Account;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired(required = false)
    private AccountMapper accountMapper;

    @Override
    public PageBean<Account> queryByPage(int code, int size) {
        PageBean<Account> pageBean = new PageBean<>();
        pageBean.setCode((code-1)*size);
        pageBean.setSize(size);
        List<Account> accounts = accountMapper.queryByPage(pageBean);
        pageBean.setRows(accounts);
        Integer totalAccounts = accountMapper.countAccountNumber();
        Integer total = 1;
        if (totalAccounts % size != 0) {
            total = totalAccounts/size + 1;
        }else {
            total = totalAccounts/size;
        }
        pageBean.setTotal(total);
        return pageBean;
    }

    @Override
    public List<Account> queryAll() {
        return accountMapper.queryAll();
    }

    @Override
    public Account queryById(Integer id) {
        return accountMapper.queryById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResult update(Account account) {
        Boolean result = accountMapper.update(account);
        return ManagerResult.ok(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResult insert(Account account) {
        Boolean result = accountMapper.insert(account);
        return ManagerResult.ok(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResult delete(Integer id) {
        Boolean result = accountMapper.delete(id);
        return ManagerResult.ok(result);
    }

    @Override
    public void findAccountByCondition(PageHelper<Account> pageHelper) {
        pageHelper.setData(accountMapper.findAccountByCondition(pageHelper));
        pageHelper.setRecordsFiltered(accountMapper.filterAccountCount(pageHelper));
        pageHelper.setRecordsTotal(accountMapper.countAccountNumber());
    }
}
